package com.xty.forum.controller;

import com.xty.forum.common.AppResult;
import com.xty.forum.common.ResultCode;
import com.xty.forum.model.User;
import com.xty.forum.services.IUserService;
import com.xty.forum.utils.MD5Utils;
import com.xty.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description TODO
 * @ClassName UserController
 * @Author RUHUA
 * @Data 2025/11/10 8:27
 */

@Tag(name = "用户接口")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 重复密码
     * @return
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register(@Parameter(description = "用户名") @RequestParam("username") @NotNull String username,
                              @Parameter(description = "昵称") @RequestParam("nickname") @NotNull String nickname,
                              @Parameter(description = "密码") @RequestParam("password") @NotNull String password,
                              @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat) {
//        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
//        || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        // 校验两次密码是否相同
        if(!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐
        String salt = UUIDUtil.UUID_32();
        //生成密文
        String ciphertext = MD5Utils.md5Salt(password, salt);
        user.setPassword(ciphertext);
        user.setSalt(salt);
        //调用Services层
        userService.createNormalUser(user);
        //返回成功
        return AppResult.success();
    }
}
